package edu.ccut.saturn.studio.saturndata.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.ccut.saturn.studio.database.model.DBConnection;
import edu.ccut.saturn.studio.database.model.DBConnectionProvider;
import edu.ccut.saturn.studio.database.model.DBConnection.DBConnectionListener;

public class DictManager {

	private static Map<String, List<String>> dictNams = new HashMap<String, List<String>>();

	public static interface DictManagerListener {
		public void onGetDict(List<String> dicts);
	}

	public static void getDictNames(String dbConnectionName,
			final DictManagerListener listener) {

		final String name = dbConnectionName;

		try {
			if (!dictNams.containsKey(name)) {
				DBConnection dbConnection = DBConnectionProvider.getInstance()
						.getConnection(name);
				if (dbConnection != null) {
					dbConnection.getConnectionAsync(new DBConnectionListener() {

						public void onGetConnection(Connection conn) {
							PreparedStatement preparedStatement = null;
							ResultSet resultSet = null;

							List<String> dicts = new ArrayList<String>();
//							String sqlLanguage = " select TYPE from SATURN_DICT where status = 0 ";
							String sqlLanguage = " select DISTINCT TYPE from SATURN_DICT_TYPE ";
							try {
								if (conn != null) {
									preparedStatement = conn
											.prepareStatement(sqlLanguage);
									resultSet = preparedStatement
											.executeQuery();

									while (resultSet.next()) {
										String dictName = resultSet
												.getString("TYPE");
										dicts.add(dictName);
									}

									dictNams.put(name, dicts);
								}
							} catch (Exception e) {
								e.printStackTrace();
							} finally {
								try {
									if (conn != null) {
										conn.close();
									}

									if (resultSet != null) {
										resultSet.close();
									}
									if (preparedStatement != null) {
										preparedStatement.close();
									}
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}
					});
				}
			}
		} finally {
			if (listener != null) {
				listener.onGetDict(dictNams.get(name));
			}
		}
	}
}
